<template>
  <q-input
    :label="label"
    :style="{ width: width + 'px', height: '40px' }"
    @clear="onClear"
    autocomplete="off"
    clearable
    dense
    filled
    ref="input"
    v-model="triggerModel"
    dark
    color="grey-5"
  >
    <q-popup-proxy @keyup.enter="onConfirm" v-model="open">
      <div class="q-pt-md q-pl-md">
        <q-btn-toggle
          :options="[
            { label: '最近', value: 'recent' },
            { label: '区间', value: 'between' },
          ]"
          color="white"
          text-color="primary"
          toggle-color="primary"
          unelevated
          v-model="direction"
        />
      </div>
      <div class="q-pa-md q-gutter-md">
        <!-- 最近 -->
        <template v-if="direction === 'recent'">
          <div class="row">
            <q-input
              @keyup.enter="onConfirm"
              autocomplete="off"
              autofocus
              class="q-mr-sm"
              clearable
              dense
              filled
              placeholder="时长"
              style="width: 120px"
              v-model="recent"
            />
            <q-select style="width: 96px" filled v-model="dateType" dense :options="dateTypeOptions" />
          </div>
        </template>

        <!-- 区间 -->
        <template v-else>
          <q-input autocomplete="off" filled v-model="date">
            <template v-slot:prepend>
              <q-icon name="event" class="cursor-pointer">
                <q-popup-proxy transition-show="scale" transition-hide="scale">
                  <q-date :locale="locale" v-model="date" mask="YYYY-MM-DD HH:mm">
                    <div class="row items-center justify-end">
                      <q-btn v-close-popup label="关闭" color="primary" flat />
                    </div>
                  </q-date>
                </q-popup-proxy>
              </q-icon>
            </template>

            <template v-slot:append>
              <q-icon name="access_time" class="cursor-pointer">
                <q-popup-proxy transition-show="scale" transition-hide="scale">
                  <q-time :locale="locale" v-model="date" mask="YYYY-MM-DD HH:mm" format24h>
                    <div class="row items-center justify-end">
                      <q-btn v-close-popup label="关闭" color="primary" flat />
                    </div>
                  </q-time>
                </q-popup-proxy>
              </q-icon>
            </template>
          </q-input>

          <q-input autocomplete="off" filled v-model="date2">
            <template v-slot:prepend>
              <q-icon name="event" class="cursor-pointer">
                <q-popup-proxy transition-show="scale" transition-hide="scale">
                  <q-date :locale="locale" v-model="date2" mask="YYYY-MM-DD HH:mm">
                    <div class="row items-center justify-end">
                      <q-btn v-close-popup label="关闭" color="primary" flat />
                    </div>
                  </q-date>
                </q-popup-proxy>
              </q-icon>
            </template>

            <template v-slot:append>
              <q-icon name="access_time" class="cursor-pointer">
                <q-popup-proxy transition-show="scale" transition-hide="scale">
                  <q-time :locale="locale" v-model="date2" mask="YYYY-MM-DD HH:mm" format24h>
                    <div class="row items-center justify-end">
                      <q-btn v-close-popup label="关闭" color="primary" flat />
                    </div>
                  </q-time>
                </q-popup-proxy>
              </q-icon>
            </template>
          </q-input>
        </template>

        <div>
          <q-btn class="full-width" color="primary" label="确认" @click="onConfirm" />
        </div>
      </div>
    </q-popup-proxy>
  </q-input>
</template>

<script lang="ts">
import { useQuasar } from 'quasar';
import { emitter } from 'src/emitter';
import { dayjs } from 'src/utils/dayjs';
import { defineComponent, ref } from 'vue';
import { locale } from './utils';

export default defineComponent({
  name: 'search-date',

  props: {
    label: {
      type: String,
      required: true,
    },
    field: {
      type: String,
      required: true,
    },
    id: {
      type: String,
    },
    width: {
      type: Number,
      default: 200,
    },
    prefix: {
      type: String,
      default: '',
    },
    initRecent: {
      type: Number,
    },
    initDateType: {
      type: String,
    },
  },

  setup(props) {
    const $q = useQuasar();

    const open = ref(false);
    const triggerModel = ref('');

    const direction = ref<'recent' | 'between'>('recent');
    const date = ref(dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm'));
    const date2 = ref(dayjs().format('YYYY-MM-DD HH:mm'));

    const recent = ref(1);
    const dateType = ref('天');

    const dateTypeOptions = ['分钟', '小时', '天', '周', '月', '季度', '年'];
    const dateTypeMap: Record<string, string> = {
      分钟: 'minutes',
      小时: 'hours',
      天: 'days',
      周: 'weeks',
      月: 'months',
      季度: 'quarters',
      年: 'years',
    };

    const init = (initRecent?: number, initDateType?: string) => {
      if (initRecent && initDateType) {
        recent.value = initRecent;
        dateType.value = initDateType;
        triggerModel.value = `最近 ${initRecent} ${initDateType}`;
      }
    };
    init(props.initRecent, props.initDateType);

    const onConfirm = () => {
      if (direction.value === 'recent') {
        if (Number.isNaN(Number(recent.value))) {
          return $q.notify({ message: '必须为数字', color: 'negative' });
        }
        const dayjsDateType: any = dateTypeMap[dateType.value];
        const date = dayjs().subtract(Number(recent.value), dayjsDateType).format('YYYY-MM-DD HH:mm');
        emitter.emit('table_search', { id: props.id, field: props.field, clause: date });
      } else {
        emitter.emit('table_search', { id: props.id, field: props.field, clause: date.value });
      }

      open.value = false;

      if (direction.value === 'between') {
        triggerModel.value = '(' + date.value + ' , ' + date2.value + ')';
      } else {
        triggerModel.value = `最近 ${recent.value} ${dateType.value}`;
      }
    };

    const onClear = () => {
      triggerModel.value = '';
      date.value = dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm');
      date2.value = dayjs().format('YYYY-MM-DD HH:mm');
      recent.value = 1;
      dateType.value = '天';
      init(props.initRecent, props.initDateType);
      emitter.emit('table_search', { id: props.id, field: props.field });
    };

    return {
      locale,
      recent,
      dateType,
      dateTypeOptions,
      dateTypeMap,
      direction,
      date,
      date2,
      triggerModel,
      onClear,
      onConfirm,
      open,
    };
  },
});
</script>
